package org.belkodevelop.controller;

import org.belkodevelop.controller.helper.AuthUtils;
import org.belkodevelop.controller.interceptor.UserInterceptor;
import org.belkodevelop.journal.service.JournalService;
import org.belkodevelop.role.RoleConstants;
import org.belkodevelop.user.domain.User;
import org.belkodevelop.user.service.UserService;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/doctor")
public class DoctorCabinetController {

    @Autowired
    private AuthUtils authUtils;

    @Autowired
    private DozerBeanMapper mapper;

    @Autowired
    private UserService userService;

    @Autowired
    private JournalService journalService;


    @RequestMapping({"/", "", "index.html"})
    public ModelAndView cabinet() {
        ModelAndView modelAndView = new ModelAndView("doctorCabinet");
        modelAndView.addObject(UserInterceptor.USER_OBJECT_NAME, authUtils.getCurrentUser());
        return modelAndView;
    }

    @RequestMapping("/patientCard/{patientId}.html")
    public ModelAndView patientCard(@PathVariable Long patientId, HttpServletResponse response) throws IOException {
        if (patientId != null && authUtils.getCurrentSessionUser() != null) {
            ModelAndView modelAndView = new ModelAndView("doctor/patientCard");
            User patient = userService.getUserById(patientId);
            if ((patient.getDoctor() != null && patient.getDoctor().equals(authUtils.getCurrentSessionUser()))
                    || authUtils.getCurrentSessionUser().getRoles().contains(RoleConstants.ADMIN_ROLE)) {
                modelAndView.addObject("patient", patient);
                modelAndView.addObject("journalItems", journalService.getJournalItems(null, null, patientId));
                return modelAndView;
            }
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
        return null;
    }

}
